Get factorialΒΆ
Formula: N! = N * (N - 1)!
import sys
def factorial_recursion(N):
''' Get factorial for a given N [recursion] '''
if N < 1:
return 1
else:
return N * factorial_recursion(N - 1)
def factorial_regular(N):
''' Get factorial for a given N [regular] '''
fact, x = 1, 2
while x <= N:
fact *= x
x += 1
return fact
# test
def test_fact(fact_algorithm, display = False):
print("Testing: ", fact_algorithm.__doc__)
N = 10
print("testcase #1:")
N = 10
Fact_10 = 3628800
Res = fact_algorithm(N)
if display:
# Display factorials from 1 to N
for i in range(1, N + 1):
print ('{}! = {}'.format(i, fact_algorithm(i)))
print("Ok" if Res == Fact_10 else "Fail")
# print("System stack depth = {}".format(sys.getrecursionlimit()))
if __name__ == "__main__":
# Factorial
test_fact(factorial_recursion)
print("=" * 40)
test_fact(factorial_regular, display=True)
Output:
testcase #1:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800